
import 'dart:convert' show json, jsonDecode;
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';
import 'package:simple_pwd_node/entity/record.dart';
import 'package:simple_pwd_node/model/record_model.dart';
import 'package:simple_pwd_node/util/db_utils.dart';
import 'package:uuid/uuid.dart';

class ImportPwdPage extends StatefulWidget {
  const ImportPwdPage({Key key}) : super(key: key);

  @override
  _ImportPwdPageState createState() => _ImportPwdPageState();
}

class _ImportPwdPageState extends State<ImportPwdPage> {

  var controller;

  @override
  void initState() {
    super.initState();
    controller = TextEditingController();
    controller.addListener(() {});
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('导入'),
      ),
      body: Container(
        padding: EdgeInsets.symmetric(vertical:8.0,horizontal:16.0),
        child: Column(
          children: [
            TextField(
              controller: controller,
              minLines: 10,
              maxLines: 10,
              decoration: InputDecoration(
                border: OutlineInputBorder(),
              ),
            ),
            Text('将要恢复的文本粘贴至这里'),
            ElevatedButton(
              child: Text('导入'),
              onPressed: _importData,
            )
          ],
        ),
      ),
    );
  }


   void _importData()async{
    print(controller.text);
    var list =  jsonDecode(controller.text);
    var db = await DbUtils.getInstance().openDb("db1");
    var uuid = new Uuid();
    for(var accountJson in list){
      print(accountJson);
      Record record = Record.fromJson(accountJson);
      record.id = uuid.v1().toString();
      await db.insertItem(record);
    }
    await Provider.of<RecordModel>(context, listen: false).update();
  }


}
